package com.gqs.bookstore.web.servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.gqs.bookstore.service.impl.UserServiceImpl;
import com.gqs.bookstore.util.Constants;
import com.gqs.bookstore.vo.Users;
/**
 * 一般定义成两个方法，一个负责处理计算，一个负责显示
 * @author 葛葛123
 *
 */
@SuppressWarnings("serial")
@WebServlet("/login.do")
public class LoginServlet extends BaseServlet {
	//因为login放在了WEB-INF里，所以在servlet里访问，且只能用请求转发，这是内部请求
	protected void auth(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException, SQLException {
		//登录即验证
//在baseservlet里定义过了
//				request.setCharacterEncoding("UTF-8");//只针对post有效【后台接收前台】
//				response.setCharacterEncoding("UTF-8");//【前台接收后台】
//				response.setContentType("text/html;charset=UTF-8");//servlet中必须添加的
				
				String account = request.getParameter("account");
				String password = request.getParameter("password");
				
				//Users users = null;
				//UserService userService = new UserServiceImpl();
				Users users = new UserServiceImpl().auth(account, password);
				
				HttpSession session = request.getSession();
				if(users == null){
					//注意这块上面的所有的往request里传东西的都要改成session，因为这块重定向时request把数据丢失了
					//request.setAttribute("account", "账号或密码不正确");
					session.setAttribute("account", "账号或密码不正确");
					response.sendRedirect("login.do?m=showLogin");
				}else{
					session.setAttribute("current_user", users);//注意这块用到了session，这个在一次会话中的所有页面都有效
					response.sendRedirect("home.do");//session重定向或者请求转发都可以传递数据
				}
	}
	
	protected void showLogin(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		//只有请求转发才可以访问WEB-INFO里的jsp，重定向不可以访问
		RequestDispatcher requDis = request.getRequestDispatcher(Constants.JSP_PATH+"login.jsp");
		requDis.forward(request, response);
	}
}
